<?php

namespace App\Supports;

trait ErrorTrait
{

    protected ?Error $error = null;

    /**
     * @return Error
     */
    public function getError(): Error
    {
        return $this->error;
    }

    /**
     * 设置错误.
     *
     * @param $code
     * @param string|null $message
     * @return void
     */
    public function setError($code, string $message = null): void
    {
        if ($this->error === null) {
            $this->error = new Error();
        }
        if ($code instanceof Error) {
            $this->error = $code;
        } elseif (is_numeric($code)) {
            $this->error->set((int)$code, $message);
        }
    }


    /**
     * 自定义错误.
     *
     * @param string $message
     * @return void
     */
    public function setCustomError(string $message = ''): void
    {
        if ($this->error === null) {
            $this->error = new Error();
        }

        if(empty($message)){
            $message = '操作失败';
        }

        $this->error->set(1, $message);
    }

}
